package com.navidove.web.manager.ctrl;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.navidove.appspotlight.model.bo.AppAdItem;
import com.navidove.appspotlight.model.bo.AppDictionary;
import com.navidove.appspotlight.model.bo.AppItem;
import com.navidove.appspotlight.model.bo.SysImage;
import com.navidove.appspotlight.model.bo.AppDevice.DeviceType;
import com.navidove.appspotlight.model.dao.AppDictionaryDao;
import com.navidove.appspotlight.model.dao.AppItemDao;
import com.navidove.appspotlight.model.dao.SysImageDao;
import com.navidove.appspotlight.model.service.AppAdService;
import com.navidove.appspotlight.model.service.AppDictionaryService;
import com.navidove.appspotlight.model.service.AppItemService;
import com.navidove.commons.utils.DaoPropertyEditor;
import com.navidove.commons.utils.DateUtils;
import com.navidove.commons.utils.EnhanceEnumPropertyEditor;
import com.navidove.commons.utils.I18NUtil;
import com.navidove.web.vo.JqGridPaging;

@Controller
@RequestMapping("/app/appAdItem")
public class AppAdItemQueryCtrl {
	
	protected final Logger logger = LoggerFactory.getLogger(this.getClass().getName());

	@Autowired
	private AppItemService appItemService;
	
	@Autowired
	private AppAdService appAdService;
	
	@Autowired
	private AppDictionaryService appDictionaryService;
	
	public static class Query implements Serializable {
		private static final long serialVersionUID = 351050505286016828L;
		
		private String appName;
		private String owner;
		private Long sourceId;
		private Long categoryId;
		public String getAppName() {
			return appName;
		}
		public void setAppName(String appName) {
			this.appName = appName;
		}
		public String getOwner() {
			return owner;
		}
		public void setOwner(String owner) {
			this.owner = owner;
		}
		public Long getSourceId() {
			return sourceId;
		}
		public void setSourceId(Long sourceId) {
			this.sourceId = sourceId;
		}
		public Long getCategoryId() {
			return categoryId;
		}
		public void setCategoryId(Long categoryId) {
			this.categoryId = categoryId;
		}
		
	}
	
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(DateUtils.DEFAULT_DATE_PATTERN);
        dateFormat.setLenient(false);        
        binder.registerCustomEditor(AppDictionary.class, DaoPropertyEditor.getInstance(AppDictionaryDao.class));
        binder.registerCustomEditor(AppItem.class, DaoPropertyEditor.getInstance(AppItemDao.class));
        binder.registerCustomEditor(SysImage.class, DaoPropertyEditor.getInstance(SysImageDao.class));
        binder.registerCustomEditor(DeviceType.class, new EnhanceEnumPropertyEditor(DeviceType.class));
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
    }
    
    @ModelAttribute("paging")
    public JqGridPaging createDisplaytagPaging() {
        return new JqGridPaging();
    }
    
    @ModelAttribute("query")
    public Query createQuery() {
        return new Query();
    }
    
    @ModelAttribute
    public void reset(Model model, @RequestParam(value="id", required=false) Long id) {
    	AppAdItem appAdItem = null;
    	if (id == null) {
    		appAdItem = new AppAdItem();
    	} else {
    		appAdItem = appAdService.getAppAdItem(id);
    	}
    	
    	model.addAttribute("appAdItem", appAdItem);
        model.addAttribute("query", createQuery());
        model.addAttribute("paging", createDisplaytagPaging()); 
    }

    @RequestMapping("/init")
    public String init(Model model) {
    	List<AppAdItem> appAdItemList = appAdService.getAppAdItemList(null, null);
    	model.addAttribute("appAdItemList", appAdItemList);
    	return "/app/appAdItem_list";
    }    
    
    @RequestMapping("/add")
    public String add(Model model) {
    	return "/app/appAdItem_edit";
    }    
    
    @RequestMapping("/edit")
    public String edit(Model model) {       
    	return "/app/appAdItem_edit";
    }    
    
    @ResponseBody
    @RequestMapping("/save")
    public Map<String, Object> save(Model model, 
    		@ModelAttribute("appAdItem") AppAdItem appAdItem,
    		@RequestParam("imageFile") MultipartFile imageFile,
    		@RequestParam(value="adUrl", required=false) String adUrl,
    		@RequestParam(value="appName", required=false) String appName,
    		@RequestParam(value="target") String target) {

        String success = I18NUtil.getMsg("dialog.message.data.param.success", I18NUtil.getMsg("button.save"));
        String failure = I18NUtil.getMsg("dialog.message.data.param.failure", I18NUtil.getMsg("button.save"));
        
        Map<String, Object> rtnVal = new HashMap<String, Object>();        
 
        try {
        	if (("appName".equals(target)&&StringUtils.isBlank(adUrl))
        			||("appName".equals(target) && StringUtils.isBlank(appName))) {
        		throw new Exception();
        	}
        	if ("appName".equals(target)) {
        		AppItem appItem = appItemService.getAppItem(appName);
        		if (appItem == null) {
        			throw new IllegalStateException(I18NUtil.getMsg("dialog.message.data.not.exists.param", 
        					I18NUtil.getMsg("bo.AppAdItem.appItem")));
        		}
        		appAdItem.setAppItem(appItem);
        		appAdItem.setAdUrl(null);
        	} else if ("adUrl".equals(target)) {
        		appAdItem.setAppItem(null);
        		appAdItem.setAdUrl(adUrl);
        	}
        	
        	appAdService.saveAppAdItem(appAdItem, imageFile);
            rtnVal.put("message", success);
            rtnVal.put("success", Boolean.TRUE);
            rtnVal.put("data", appAdItem.getId());
        } catch (IllegalStateException e) {
            logger.error(e.getMessage(),e);
            rtnVal.put("message", e.getMessage());
            rtnVal.put("success", Boolean.FALSE);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            rtnVal.put("message", failure);
            rtnVal.put("success", Boolean.FALSE);
        }

        return rtnVal;
    }  
    
    @ResponseBody
    @RequestMapping("/delete")
    public Map<String, Object> delete(Model model, @ModelAttribute("id") Long id) {

        String success = I18NUtil.getMsg("dialog.message.data.param.success", I18NUtil.getMsg("button.delete"));
        String failure = I18NUtil.getMsg("dialog.message.data.param.failure", I18NUtil.getMsg("button.delete"));
        
        Map<String, Object> rtnVal = new HashMap<String, Object>();        
 
        try {
            appAdService.deleteAppAdItem(id);
            rtnVal.put("message", success);
            rtnVal.put("success", Boolean.TRUE);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            rtnVal.put("message", failure);
            rtnVal.put("success", Boolean.FALSE);
        }

        return rtnVal;
    }    
    
    @ResponseBody
    @RequestMapping("/sort")
    public Map<String, Object> sort(Model model, 
    		@RequestParam("sort") Long[] ids) {
    	
    	appAdService.sort(ids);
    	return new HashMap<String, Object>();
    }  
}
